﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

using TYAJZWeb.Data;
using Newtonsoft.Json;
using TYAJZWeb.Models;
using TYAJZWeb.Utils;

namespace TYAJZWeb
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


            routes.MapRoute(
                "List", // Route name
                "{controller}/List/{page}", // URL with parameters
                new { controller = "Home", action = "List", page = 1 } // Parameter defaults
            );

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            InitAllSystemVariables();

        }

        private void InitAllSystemVariables()
        {
            using (TYAJZDataContext context = new TYAJZDataContext())
            {
                context.SystemVariables.ToList().ForEach(t =>
                    {
                        SystemVariableEnums type = SystemVariableEnums.NONE;
                        Enum.TryParse<SystemVariableEnums>(t.Type, out type);
                        switch (type)
                        {
                            case SystemVariableEnums.Print:
                                Application.Add(type.ToString(), JsonConvert.DeserializeObject<PrintEditModel>(t.Value));
                                break;
                            case SystemVariableEnums.AJZInfo:
                                Application.Add(type.ToString(), JsonConvert.DeserializeObject<AJZInfoEditModel>(t.Value));
                                break;
                        }
                    });
            }
        }
    }
}